/*
 * $Id: cleanup.c 7557b5d4d82b 2012/12/02 09:07:16 pgurumur $
 *
 * Copyright (c) 2006, 2007, 2008 Prabhu Gurumurthy <pgurumur@gmail.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include "sshc.h"

void
ssh_shutdown()
{
   if (sshc) {
      if (sshc->channel) {
         if (got_channel) {
            if (libssh2_channel_send_eof(sshc->channel) < 0)
               warning(0, "libssh2_channel_send_eof()");
            if (libssh2_channel_close(sshc->channel) < 0) 
               warning(0, "libssh2_channel_close()");

            if (libssh2_channel_wait_closed(sshc->channel) < 0)
               warning(0, "libssh2_channel_wait_closed()");

            libssh2_channel_free(sshc->channel);
         }
      }
      
      if (sshc->session) {
         libssh2_session_disconnect(sshc->session, DEF_MESG);
         libssh2_session_free(sshc->session);
      }

   }
}

void
cleanup()
{
   if (sshc) {
      logit(0, "in %s", __func__);

      blocking(fileno(stdin), 1);

      ssh_shutdown();
      logit(0, "ssh session and channel shutdown complete");

      if (sshc->sock)
         close(sshc->sock);

      logit(0, "socket no %d closed", sshc->sock);

      if (sshc->tempfile)
         unlink(sshc->tempfile);

      logit(0, "tempfile unlinked");

      if (sshc->input) {
         logit(0, "fd %d closed", fileno(sshc->input));
         fclose(sshc->input);
      }

      logit(0, "input file closed");

      free(sshc);

      logit(0, "main structure freed");
   }


   closelog();
}

